package com.cskaoyan.service;

import com.cskaoyan.bean.data.CartCheckoutData;
import com.cskaoyan.bean.data.CartIndexData;
import com.cskaoyan.bean.data.CartStat;
import com.cskaoyan.bean.vo.CartAddVo;
import com.cskaoyan.mapper.*;
import com.cskaoyan.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Description
 * @Author zoe ling
 * @Date 2024/6/12
 */
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    MarketCartMapper cartMapper;
    @Autowired
    MarketGoodsMapper goodsMapper;
    @Autowired
    MarketGoodsProductMapper productMapper;
    @Autowired
    MarketCouponMapper couponMapper;
    @Autowired
    MarketCouponUserMapper couponUserMapper;
    @Autowired
    MarketAddressMapper addressMapper;
    @Autowired
    GoodsService goodsService;
    @Autowired
    ProductService productService;
    @Autowired
    CouponUserService couponUserService;
    @Autowired
    CouponService couponService;
    @Autowired
    SystemService systemService;
    @Autowired
    AddressService addressService;

    @Override
    public long goodscount(int userId) {
        MarketCartExample example = new MarketCartExample();
        example.createCriteria().andUserIdEqualTo(userId)
                .andDeletedEqualTo(false);
        long count = cartMapper.countByExample(example);
        return count;
    }
    @Override
    public CartIndexData index(Integer userId) {
        //查询当前用户的所有购物车记录
        List<MarketCart> marketCarts = this.userCartList(userId);
        CartStat stat = CartStat.stat(marketCarts);
        CartIndexData data = CartIndexData.builder()
                .cartList(marketCarts)
                .cartTotal(stat)
                .build();

        return data;
    }
    @Override
    public List<MarketCart> userCartList(Integer userId) {
        MarketCartExample example = new MarketCartExample();
        example.createCriteria().andUserIdEqualTo(userId)
                .andDeletedEqualTo(false);
        List<MarketCart> marketCarts = cartMapper.selectByExample(example);
        return marketCarts;
    }
    @Override
    public CartIndexData checked(Integer userId, Map<String, Object> map) {
        Integer productIds = (Integer) map.get("productIds");
        boolean isChecked = (boolean) map.get("isChecked");
        // MarketCartExample example = new MarketCartExample();
        // example.createCriteria().andProductIdEqualTo(productIds)
        //         .andDeletedEqualTo(false);
        // MarketCart marketCart = new MarketCart();
        // marketCart.setChecked(isChecked);
        // cartMapper.updateByExampleSelective(marketCart,example);

        List<MarketCart> marketCarts = this.userCartList(userId);
        CartStat stat = CartStat.stat(marketCarts);
        CartIndexData data = CartIndexData.builder()
                .cartList(marketCarts)
                .cartTotal(stat)
                .build();
        return data;
    }

    @Override
    public MarketCart find(Integer userId, Integer goodsId, Integer productId) {
        MarketCartExample example = new MarketCartExample();
        example.createCriteria()
                .andUserIdEqualTo(userId)
                .andGoodsIdEqualTo(goodsId)
                .andProductIdEqualTo(productId)
                .andDeletedEqualTo(false);
        List<MarketCart> marketCarts = cartMapper.selectByExample(example);
        return marketCarts!=null&&marketCarts.size()==1?marketCarts.get(0):null;
    }
    @Override
    public int create(CartAddVo cartAddVo, Integer userId) {
        Integer goodsId = cartAddVo.getGoodsId();
        Integer productId = cartAddVo.getProductId();
        Short number = cartAddVo.getNumber();
        MarketGoods marketGoods = goodsService.findById(goodsId);
        MarketGoodsProduct product=productService.finById(productId);

        Date current = new Date();
        MarketCart marketCart = MarketCart.builder()
                .userId(userId)
                .checked(true)
                .goodsId(goodsId)
                .goodsName(marketGoods.getName())
                .goodsSn(marketGoods.getGoodsSn())
                .productId(productId)
                .picUrl(marketGoods.getPicUrl())
                .price(product.getPrice())
                .number(number)
                .specifications(Arrays.toString(product.getSpecifications()))
                .addTime(current)
                .updateTime(current)
                .deleted(false)
                .build();
        return cartMapper.insertSelective(marketCart);
    }
    @Override
    public void modify(MarketCart marketCart) {
        //根据id更新
        cartMapper.updateByPrimaryKeySelective(marketCart);


    }

    @Override
    public boolean updateChecked(Integer userId, List<Integer> productIds, Boolean isChecked) {
        if (productIds!=null&&productIds.size()==1){
            Integer productId = productIds.get(0);
            MarketCartExample example = new MarketCartExample();
            example.createCriteria()
                    .andProductIdEqualTo(productId)
                    .andUserIdEqualTo(userId);

            MarketCart marketCart = new MarketCart();
            marketCart.setChecked(isChecked);
            int affectRows = cartMapper.updateByExampleSelective(marketCart, example);
            return affectRows==1?true:false;

        }
        return false;
    }

    @Override
    public MarketCart getCartId(Integer userId, CartAddVo cartFastaddVo) {
        Integer goodsId = cartFastaddVo.getGoodsId();
        Integer productId = cartFastaddVo.getProductId();
        Short number = cartFastaddVo.getNumber();
        //快速添加到cart表，并返回cart表中的id
       create(cartFastaddVo, userId);
        MarketCartExample example = new MarketCartExample();
        example.createCriteria()
                .andUserIdEqualTo(userId)
                .andGoodsIdEqualTo(goodsId)
                .andProductIdEqualTo(productId)
                .andNumberEqualTo(number)
                .andDeletedEqualTo(false);
        List<MarketCart> marketCarts = cartMapper.selectByExample(example);
        return marketCarts!=null&&marketCarts.size()==1?marketCarts.get(0):null;
    }

    @Override
    public CartCheckoutData checkout(Integer userId,Integer cartId,Integer addressId,Integer couponId,Integer userCouponId) {
        MarketAddress marketAddress;
        Integer marketAddressId;
        if (addressId==0){
            marketAddress= addressService.queryDefault(userId);
            marketAddressId = marketAddress.getId();
        }else {
            marketAddress = addressMapper.selectByPrimaryKey(addressId);
            marketAddressId = marketAddress.getId();
        }
        //选中商品总价
        BigDecimal checkedGoodsAmount;
        List<MarketCart> marketGoodsList;
        if (cartId==0){
            CartIndexData cartIndexData = index(userId);
            List<MarketCart> AllmarketGoodsList= cartIndexData.getCartList();
            marketGoodsList = AllmarketGoodsList.stream().filter(MarketCart::getChecked).toList();
            checkedGoodsAmount = cartIndexData.getCartTotal().getCheckedGoodsAmount();
        }else {
            MarketCart marketCart = cartMapper.selectByPrimaryKey(cartId);
            Short number = marketCart.getNumber();
            BigDecimal price = marketCart.getPrice();
            checkedGoodsAmount=price.multiply(BigDecimal.valueOf(number));
            // marketGoodsList=goodsService.queryByCartId(cartId);
            MarketCartExample example = new MarketCartExample();
            example.createCriteria().andIdEqualTo(cartId)
                            .andDeletedEqualTo(false);
            marketGoodsList = cartMapper.selectByExample(example);
        }
        //算运费
        BigDecimal freightPrice=systemService.getFreightPrice(checkedGoodsAmount);
        Integer availableCouponLength=-1;
        BigDecimal couponPrice=BigDecimal.valueOf(0);
        if (couponId==-1){
            //获取该用户可以使用的优惠券
            availableCouponLength=couponUserService.getAvailableCouponLength(userId,couponId);
        } else if (couponId==0) {
            //为用户选择优惠力度最大的优惠券
            //usercoupon中得到拥有的couponid
            List<MarketCouponUser>availCouponList=couponUserService.getCouponList(userId);
            List<Integer> couponIdlist = availCouponList.stream().map(MarketCouponUser::getCouponId).toList();
            //在coupon表中选择满足优惠券最低使用门槛，且优惠力度最大的券Optimal Solution
            MarketCoupon maxDiscountCoupon=couponService.getOptimalSolution(couponIdlist,checkedGoodsAmount);


        }else {
            //获取订单可以使用的优惠券金额couponPrice
            MarketCoupon marketCoupon=couponService.getDiscountMoney(couponId);
            if (marketCoupon!=null){
                couponPrice = marketCoupon.getDiscount();

            }

        }

        //orderTotalPrice=goodsTotalPrice+freightPrice
        BigDecimal TotalPrice=checkedGoodsAmount.add(freightPrice);
        //actualPrice=orderTotalPrice-couponPrice
        BigDecimal actualPrice=TotalPrice.subtract(couponPrice);


        return CartCheckoutData.builder()
                .actualPrice(actualPrice)
                .addressId(marketAddressId)
                .availableCouponLength(availableCouponLength)
                .cartId(cartId)
                .checkedAddress(marketAddress)
                .checkedGoodsList(marketGoodsList)
                .couponId(couponId)
                .couponPrice(couponPrice)
                .freightPrice(freightPrice)
                .goodsTotalPrice(checkedGoodsAmount)
                .orderTotalPrice(actualPrice)
                .userCouponId(userCouponId)
                .build();
    }

    @Override
    public MarketCart selectByGoodsId(Integer userId, CartAddVo cartFastaddVo) {
        Integer goodsId = cartFastaddVo.getGoodsId();
        Integer productId = cartFastaddVo.getProductId();
        Short number = cartFastaddVo.getNumber();
        MarketCartExample example = new MarketCartExample();
        example.createCriteria()
                .andUserIdEqualTo(userId)
                .andGoodsIdEqualTo(goodsId)
                .andDeletedEqualTo(false);
        MarketCart marketCart = new MarketCart();
        marketCart.setNumber(number);
        // marketCart.setDeleted(true);
         cartMapper.updateByExampleSelective(marketCart, example);
        List<MarketCart> marketCarts = cartMapper.selectByExample(example);
        return marketCarts!=null&&marketCarts.size()==1?marketCarts.get(0):null;
    }

    @Override
    public MarketCart findById(Integer cartId) {
        MarketCartExample example = new MarketCartExample();
        example.createCriteria()
                .andIdEqualTo(cartId)
                .andDeletedEqualTo(false);
        List<MarketCart> marketCarts = cartMapper.selectByExample(example);
        return marketCarts!=null&&marketCarts.size()==1?marketCarts.get(0):null;
    }

    @Override
    public boolean delById(Integer cartId) {
        //4.删除购物车中记录marketCart
        MarketCart marketCart = new MarketCart();
        marketCart.setDeleted(true);

        MarketCartExample example = new MarketCartExample();
        example.createCriteria()
                .andIdEqualTo(cartId)
                .andDeletedEqualTo(false);
        int affectRows = cartMapper.updateByExampleSelective(marketCart, example);
        return affectRows==1?true:false;
    }


}
